
import { Form, FormInstance, InputNumber } from '@arco-design/web-react';
import { isNil } from 'lodash';
import React, { memo, useCallback, useContext, useEffect, useRef, useState } from 'react';
const FormItem = Form.Item;

const EditableContext = React.createContext<{ form?: FormInstance }>({});

import './index.scss';

/**
 * 表格可编辑行
 * @returns 
 */
const EditableRow = memo(
    function (props: any) {
        const { children, record, className, addChange, listenChange, removeChange, ...rest } = props;

        const [form] = Form.useForm();

        /**
         * 检查数据是否变化
         */
        const checkValueHasChange = useCallback((value: any) => {
            const key = Object.keys(value)[0];
            const oldVal = record[key];
            const newVal = value[key];

            if (oldVal !== newVal) {
                listenChange && listenChange(record.id, value);
                addChange && addChange(record.id, +newVal);
            } else if (!isNil(newVal)) {
                removeChange(record.id, oldVal);
            }
        }, [record, addChange, removeChange]);

        return (
            <EditableContext.Provider
                value={{
                    form
                }}
            >
                <Form
                    style={{ display: 'table-row' }}
                    onChange={checkValueHasChange}
                    children={children}
                    form={form}
                    wrapper='tr'
                    wrapperProps={rest}
                    className={`${className} editable-row`}
                />
            </EditableContext.Provider>
        );
    }
);

/**
 * 编辑表格
 * @returns 
 */
const EditableCell = memo(
    function (props: any) {
        let { children, className, rowData, column, onSave, onChange } = props;

        const { form } = useContext(EditableContext);
        /**
         * 编辑状态
         */
        const [editing, setEditing] = useState(false);

        if (column.rowData) {
            rowData = column.rowData(rowData)
        }

        // 更新表格值
        const updateCellValue = () => {
            form!.validate([column.dataIndex], (errors, values) => {
                if (!errors || !errors[column.dataIndex]) {
                    const newVal = values![column.dataIndex];
                    const oldVal = rowData[column.dataIndex];
                    if (newVal !== oldVal) {
                        onSave && onSave({ ...rowData, ...values });
                    }
                    setEditing(!editing);
                }
            });
        };

        const handleOnChange = (val: number) => {
            form!.validate([column.dataIndex], (errors, values) => {
                if (!errors || !errors[column.dataIndex]) {
                    if (onChange && !onChange({ ...rowData, ...values }, column.dataIndex)) {
                        const oldVal = rowData[column.dataIndex];
                        form!.setFieldValue(column.dataIndex, oldVal)
                    }
                }
            })

        };
        /**
         * 进入编辑
         */
        const enterEdit = useCallback(
            () => {
                if (column.editable) {
                    form!.setFieldValue(column.dataIndex, rowData[column.dataIndex]);
                    setEditing(!editing)
                }
                if (column.handleEditable) {
                    form!.setFieldValue(column.dataIndex, rowData[column.dataIndex]);
                    setEditing(column.handleEditable(rowData))
                }
            },
            [column, form]
        );

        // 编辑模式
        if (editing) {
            return (
                <div>
                    <FormItem
                        style={{ marginBottom: 0, ...(column?.formStyle ?? {}) }}
                        labelCol={{ span: 0 }}
                        wrapperCol={{ span: 24 }}
                        initialValue={rowData[column.dataIndex]}
                        field={column.dataIndex}
                        rules={column?.rules || [{ required: true, message: '必填' }]}
                        shouldUpdate={false}
                    >
                        <InputNumber
                            min={column?.min ?? -Infinity}
                            max={column?.max ?? Infinity}
                            size={column?.iNsize || 'small'}
                            precision={column?.precision ?? 1}
                            step={column?.step ?? 1}
                            prefix={column?.prefix || ""}
                            hideControl={column?.hideControl ?? false}
                            suffix={column?.suffix ? column.suffix(rowData) : false}
                            // mode='button'
                            //style={{width:'70%'}}
                            onFocus={evt => { evt.target.select(); }} {...(column.editProps || {})}
                            onChange={handleOnChange}
                            onBlur={() => { column?.isBlur && updateCellValue(); }}
                            onPressEnter={() => { column?.isBlur && updateCellValue(); }}
                            type="number"
                        />

                    </FormItem>
                </div>
            );
        }

        return (
            <div
                className={column.editable ? `editable-cell ${className}` : className}
                onClick={enterEdit}
            >
                {children}
            </div>
        );
    }
);

export {
    EditableCell,
    EditableRow
};

